﻿using MongoDB.Driver;
using MongoDB.Driver.GridFS;
using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Configuration;
//using System.Collections.Generic
//using System.Linq
//using System.Text
//using System.Threading


namespace NCRE学生考试端V1._0
{
    public class MongoHelper
    {
        private readonly string connectionString = ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString.ToString(); 
        //设置连接超时时间
        private readonly int CONNECT_TIME_OUT = 1200;
        readonly MongoServer server;
        readonly MongoDatabase database;
        public MongoHelper(string strDataBase)
        {
            server = MongoServer.Create(connectionString);
            //server = MongoClient.GetServer()
            database = server.GetDatabase(strDataBase);

            MongoClientSettings mongoSetting = new MongoClientSettings();
            mongoSetting.ConnectTimeout = new TimeSpan(CONNECT_TIME_OUT * TimeSpan.TicksPerSecond);//设置超时连接
        }

        #region 上传学生答题记录的压缩包到数据库Upload
        /// <summary>
        /// 上传学生答题记录的压缩包到数据库Upload
        /// </summary>
        /// <param name="strSourceFile">学生答题记录的压缩包，例如D:\\11070141021</param>
        /// <param name="strFileName">数据库中保存的文件名称(使用学好).例如：11070141021</param>
        /// <param name="strGridFS">GRIDFS保存的数据集合的名称</param>
        public Boolean Upload(string strSourceFile, string strFileName, string strGridFS)
        {
            Boolean flag = false;
                //定义一个本地文件的路径字符串
                string localFileName = strSourceFile;
                //定义mongoDB数据库中文件的名称
                string mongoDBFileName = strFileName;
                //设置GridFS文件中对应的集合前缀名
                MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = strGridFS };
                //实例化一个GridFS
                MongoGridFS gridfs = new MongoGridFS(database, fsSetting);
                //将本地文件上传到mongoDB中去,以默认块的大小256KB对文件进行分块
                gridfs.Upload(localFileName, mongoDBFileName);
                flag = true;
            return flag;
        } 
        #endregion

        #region 下载指定的文件DownLoad
        /// <summary>
        /// 下载指定的文件DownLoad
        /// </summary>
        /// <param name="strGridFs"></param>
        /// <param name="strFileName"></param>
        public void DownLoad( string strFileName,string strGridFs)
        {
           
                //设置GridFS文件中对应的集合前缀名
                MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = strGridFs };
                //实例化一个GridFS
                MongoGridFS fs = new MongoGridFS(database, fsSetting);
                //根据学好拼接出一个压缩包的名称
                string fileName = strFileName;
                fs.Download(fileName);
                  
        } 
        #endregion

        #region 获取集合GetInfoList
        /// <summary>
        /// 获取集合GetInfoList
        /// </summary>
        /// <param name="fileName">查询的关键字，以学好信息为准</param>
        /// <param name="strGridFs">GridFS的名称</param>
        /// <returns></returns>
        public string GetInfoList(string fileName, string strGridFs)
        {
            MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = strGridFs };
            MongoGridFS fs = new MongoGridFS(database, fsSetting);

            database.GetCollection(strGridFs + ".files");

            string filesJSON = "[";

            //排序方法-按照时间降序排列
            SortByDocument sort = new SortByDocument { 
                {"filename", 1},
                {"uploadDate", -1}
            };

            //关键字查询
            Regex findby = new Regex(@".*" + fileName + ".*", RegexOptions.IgnoreCase);
            QueryDocument query = new QueryDocument
            {
                {"filename", findby}
            };

            MongoCursor<MongoGridFSFileInfo> docList = fs.Find(query).SetSortOrder(sort);
            foreach (MongoGridFSFileInfo doc in docList)
            {
                UInt32 length = Convert.ToUInt32(doc.Length);
                string size = null;
                if (length > 1024 * 1024)
                    size = ((double)length / 1024 / 1024).ToString("F2") + "MB";
                else if (length > 1024)
                    size = ((double)length / 1024).ToString("F2") + "KB";
                else
                    size = length.ToString() + "B";
                filesJSON += "{\"name\":\"" + doc.Name + "\",\"lastModify\":\"" + Convert.ToDateTime(doc.UploadDate).ToLocalTime().ToString() + "\", \"size\":\"" + size + "\"},";

            }
            if (filesJSON.EndsWith(","))
            {
                filesJSON = filesJSON.Substring(0, filesJSON.Length - 1);
            }
            filesJSON += "]";

            return filesJSON;

        } 
        #endregion


        #region 删除文件Delete
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <param name="strGridFS">GridFS的学院名称</param>
        public void Delete(string fileName, string strGridFS)
        {
            MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = strGridFS };

            MongoGridFS fs = new MongoGridFS(database, fsSetting);
            fs.Delete(fileName);
        } 
        #endregion
    }
}
